package com.cheng.sell.service.impl;

import com.cheng.sell.dto.OrderMasterDTO;
import com.cheng.sell.enums.ResultEnum;
import com.cheng.sell.exception.SellException;
import com.cheng.sell.service.BuyerService;
import com.cheng.sell.service.OrderMasterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * Description:
 * </p>
 *
 * @author chengxintao
 * @version 1.0
 * <p>
 * <p>
 * History:
 * <p>
 * Date                 Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2018/9/6         chengxintao          1.0         To create
 * </p>
 * @see
 * @since
 */
@Service
@Slf4j
public class BuyerServiceImpl implements BuyerService {
    @Autowired
    private OrderMasterService service;

    @Override
    public OrderMasterDTO findOrderOne(String openid, String orderId) {
        return checkOrderOwner(openid, orderId);
    }

    @Override
    public OrderMasterDTO cancelOrder(String openid, String orderId) {
        OrderMasterDTO orderMasterDTO = checkOrderOwner(openid, orderId);
        if (null == orderMasterDTO) {
            log.error("【取消订单】查不到订单,orderId={}", orderId);
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }
        return service.cancel(orderMasterDTO);
    }

    private OrderMasterDTO checkOrderOwner(String openid, String orderId) {
        OrderMasterDTO masterDTO = service.query(orderId);
        if (!masterDTO.getBuyerOpenid().equalsIgnoreCase(openid)) {
            log.error("【查询订单】订单的openid不一致,openid={},orderDTO={}", openid, masterDTO);
            throw new SellException(ResultEnum.ORDER_OWNER_ERROR);
        }
        return masterDTO;
    }
}
